package com.example.controller.api;

import com.example.config.Config;
import com.example.service.FileMgr;
import com.example.utils.Tools;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestController
public class ApiController {
    @RequestMapping("/api/ping")
    public String ping() {
        return "毕升文档 api demo server. status: ok";
    }
    @RequestMapping("/api/queryFileList")
    public ArrayList<Map<String,String>> queryFileList() {
        Map<String,Map<String,String>> files = FileMgr.queryFileList();
        ArrayList<Map<String,String>>fileList = new ArrayList<Map<String,String>>();
        for (Map<String,String> file : files.values()) {
            Map<String,String> fileInfo = new HashMap<String,String>();
            fileInfo.put("docId",file.get("docId"));
            fileInfo.put("title",file.get("title"));
            fileInfo.put("fetchUrl",file.get("fetchUrl"));
            fileList.add(fileInfo);
        }
        return fileList;
    }

    private Map<String,String> onGetBishengApi(String docId, String userId, String suffix) {
        Map<String, String> map = new HashMap<String, String>();
        try{
            String callback = Tools.encodeBase64(String.format("%s/api/fileAcl/%s/%s", Config.getConfig().getEditorCaller(),docId,userId).getBytes());
            String sign = Tools.byteArrToHex(Tools.encryptionHMACMD5(callback,Config.getConfig().getApiKey()));
            String url = String.format("%s/apps/editor/%s?callURL=%s&sign=%s",Config.getConfig().getEditorHost(),suffix,callback,sign);
            map.put("url",url);
        }catch (Exception e){
            map.put("error",e.toString());
        }
        return map;
    }

    @RequestMapping(value="/api/file/view/{docId}/{uid}",method=RequestMethod.GET)
    public Map<String,String> viewFile(@PathVariable("docId") String docId, @PathVariable("uid") String uid) {
        return onGetBishengApi(docId,uid,"openPreview");
    }

    @RequestMapping(value="/api/file/edit/{docId}/{uid}",method=RequestMethod.GET)
    public Map<String,String> editFile(@PathVariable("docId") String docId, @PathVariable("uid") String uid) {
        return onGetBishengApi(docId,uid,"openEditor");
    }

    @RequestMapping(value="/api/fileAcl/{docId}/{uid}",method=RequestMethod.GET)
    public Map<String,Map<String,Object>> fileAcl(@PathVariable("docId") String docId, @PathVariable("uid") String uid) {
        Map<String,String> fileInfo = FileMgr.queryfile(docId);
        Map<String,Map<String,Object>> result= new HashMap<String,Map<String,Object>>();
        if(fileInfo==null){
            return result;
        }
        Map<String,Object> doc = new HashMap<String,Object>();
        doc.put("docId",fileInfo.get("docId"));
        doc.put("title",fileInfo.get("title"));
        doc.put("fetchUrl",String.format("%s/api/file/%s/%s",Config.getConfig().getEditorCaller(),docId,uid));
        doc.put("fromApi",true);

        Map<String,Object> user = new HashMap<String,Object>();
        user.put("uid",uid);
        user.put("nickName",uid);
        user.put("avatar","");
        user.put("privilege",new String[]{"FILE_READ","FILE_WRITE","FILE_DOWNLOAD","FILE_PRINT"});
        result.put("doc",doc);
        result.put("user",user);
        return result;
    }

    @RequestMapping(value="/api/file/{docId}/{uid}",method=RequestMethod.GET)
    public String file(@PathVariable("docId") String docId, @PathVariable("uid") String uid,HttpServletRequest request,HttpServletResponse response) {
        Map<String,String> fileInfo = FileMgr.queryfile(docId);
        try {
            Tools.download(fileInfo.get("storage"),response);
        }catch (Exception e){
            System.out.println(e.toString());
        }

        return null;
    }

    @RequestMapping(value="/api/file/saveBack", method = RequestMethod.POST)
    public Map<String,Object> saveBack(@RequestBody Map<String,Object> info) {
        String action = (String) info.get("action");
        switch (action) {
            case "saveBack": {
                Map<String,String> data = (Map<String,String>)info.get("data");
                if (data != null) {
                    String docId = data.get("docId");
                    String docURL = data.get("docURL");

                    Map<String,String> fileInfo = FileMgr.queryfile(docId);
                    if (fileInfo != null) {
                        return new HashMap<String, Object>(){
                            {
                                put("statue",true);
                            }
                        };
                    }
                }
                break;
            }
        }
        return null;
    }
}
